import 'package:shared_preferences/shared_preferences.dart';

/// 本地缓存服务 - 用于保存未同步到服务器的待办内容
class LocalCacheService {
  static const String _draftPrefix = 'todo_draft_';
  static const String _timestampSuffix = '_timestamp';
  static const String _lastSelectedCategoryKey = 'last_selected_category_id';
  static const String _isPreviewModeKey = 'is_preview_mode';
  static const String _showCompletedKey = 'show_completed';

  /// 保存待办草稿到本地
  static Future<void> saveDraft(String todoId, String content) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_draftPrefix$todoId';
      final timestampKey = '$key$_timestampSuffix';

      await prefs.setString(key, content);
      await prefs.setInt(timestampKey, DateTime.now().millisecondsSinceEpoch);
    } catch (e) {
      // 静默失败
    }
  }

  /// 获取待办草稿
  static Future<String?> getDraft(String todoId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_draftPrefix$todoId';
      return prefs.getString(key);
    } catch (e) {
      return null;
    }
  }

  /// 删除待办草稿
  static Future<void> deleteDraft(String todoId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_draftPrefix$todoId';
      final timestampKey = '$key$_timestampSuffix';

      await prefs.remove(key);
      await prefs.remove(timestampKey);
    } catch (e) {
      // 静默失败
    }
  }

  /// 获取所有待办草稿
  static Future<Map<String, String>> getAllDrafts() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();
      final drafts = <String, String>{};

      for (final key in keys) {
        if (key.startsWith(_draftPrefix) && !key.endsWith(_timestampSuffix)) {
          final todoId = key.substring(_draftPrefix.length);
          final content = prefs.getString(key);
          if (content != null) {
            drafts[todoId] = content;
          }
        }
      }

      return drafts;
    } catch (e) {
      return {};
    }
  }

  /// 检查是否有未保存的草稿
  static Future<bool> hasDraft(String todoId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_draftPrefix$todoId';
      return prefs.containsKey(key);
    } catch (e) {
      return false;
    }
  }

  /// 清除所有草稿（调试用）
  static Future<void> clearAllDrafts() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys().where((key) => key.startsWith(_draftPrefix)).toList();

      for (final key in keys) {
        await prefs.remove(key);
      }
    } catch (e) {
      // 静默失败
    }
  }

  /// 保存最后选择的分类ID
  static Future<void> saveLastSelectedCategory(String? categoryId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (categoryId != null) {
        await prefs.setString(_lastSelectedCategoryKey, categoryId);
      } else {
        await prefs.remove(_lastSelectedCategoryKey);
      }
    } catch (e) {
      // 静默失败
    }
  }

  /// 获取最后选择的分类ID
  static Future<String?> getLastSelectedCategory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final categoryId = prefs.getString(_lastSelectedCategoryKey);
      return categoryId;
    } catch (e) {
      return null;
    }
  }

  /// 保存预览模式状态
  static Future<void> savePreviewMode(bool isPreviewMode) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_isPreviewModeKey, isPreviewMode);
    } catch (e) {
      // 静默失败
    }
  }

  /// 获取预览模式状态（默认true）
  static Future<bool> getPreviewMode() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final isPreviewMode = prefs.getBool(_isPreviewModeKey) ?? true;
      return isPreviewMode;
    } catch (e) {
      return true;
    }
  }

  /// 保存"显示已完成"状态
  static Future<void> saveShowCompleted(bool showCompleted) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_showCompletedKey, showCompleted);
    } catch (e) {
      // 静默失败
    }
  }

  /// 获取"显示已完成"状态（默认false）
  static Future<bool> getShowCompleted() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final showCompleted = prefs.getBool(_showCompletedKey) ?? false;
      return showCompleted;
    } catch (e) {
      return false;
    }
  }
}
